package com.zj.jdbc2ThreadLocal.tools;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: BeanListHandler
 * @Description: 将结果集转换成bean对象的list集合的处理器
 * @author: 孤傲苍狼
 * @date: 2014-10-5 下午12:00:06
 *
 */
public class BeanListHandler implements ResultSetHandler {
    private Class<?> clazz;
    private Map<String,String> colomnToFieldMap=new HashMap<>();
    public BeanListHandler(Class<?> clazz){
        this.clazz = clazz;
        Field[] fields=clazz.getDeclaredFields();
        for(int i=0;i<fields.length;i++){
            colomnToFieldMap.put(clazz.getName()+"."+fields[i].getName().toLowerCase(),fields[i].getName());
        }
        System.out.println(colomnToFieldMap);
    }

    public Object handler(ResultSet rs) {
        try{
            List<Object> list = new ArrayList<Object>();
            while(rs.next()){
                Object bean = clazz.newInstance();

                ResultSetMetaData  metadata = rs.getMetaData();
                int count = metadata.getColumnCount();
                for(int i=0;i<count;i++){
                    String name = metadata.getColumnName(i+1);
                    Object value = rs.getObject(name);
                    String field=colomnToFieldMap.get(clazz.getName()+"."+name.toLowerCase());
                    if(field!=null) {
                        Field f = clazz.getDeclaredField(field);//反射出类上列名对应的属性
                        f.setAccessible(true);
                        f.set(bean, value);
                    }
                }
                list.add(bean);
            }
            return list.size()>0?list:null;

        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
